<?php

if (get_magic_quotes_gpc()) {

    function stripslashes_deep($value) {
        $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);
        return $value;
    }

    $_POST   = array_map('stripslashes_deep', $_POST);
    $_GET    = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}

/**
 * 获取中文拼音
 * @param $_String
 * @param $_Code
 */
function Pinyin($_String, $_Code = 'utf8') {
    $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha" .
            "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|" .
            "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er" .
            "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui" .
            "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang" .
            "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang" .
            "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue" .
            "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne" .
            "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen" .
            "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang" .
            "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|" .
            "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|" .
            "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu" .
            "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you" .
            "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|" .
            "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo";

    $_DataValue  = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990" .
            "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725" .
            "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263" .
            "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003" .
            "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697" .
            "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211" .
            "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922" .
            "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468" .
            "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664" .
            "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407" .
            "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959" .
            "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652" .
            "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369" .
            "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128" .
            "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914" .
            "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645" .
            "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149" .
            "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087" .
            "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658" .
            "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340" .
            "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888" .
            "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585" .
            "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847" .
            "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055" .
            "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780" .
            "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274" .
            "|-10270|-10262|-10260|-10256|-10254";
    $_TDataKey   = explode('|', $_DataKey);
    $_TDataValue = explode('|', $_DataValue);

    $_Data = (PHP_VERSION >= '5.0') ? array_combine($_TDataKey, $_TDataValue) : _Array_Combine($_TDataKey, $_TDataValue);
    arsort($_Data);
    reset($_Data);

    $_String = preg_replace("/[^" . chr(228) . chr(128) . chr(128) . "-" . chr(233) . chr(191) . chr(191) . "]/u", '', $_String);

    if ($_Code != 'gb2312')
        $_String = _U2_Utf8_Gb($_String);
    $_Res    = '';

    for ($i = 0; $i < strlen($_String); $i++) {
        $_P = ord(substr($_String, $i, 1));
        if ($_P > 160) {
            $_Q = ord(substr($_String, ++$i, 1));
            $_P = $_P * 256 + $_Q - 65536;
        }
        //if (!empty($_Res)){
        //$_Res .= '';
        //}
        $_Res .= _Pinyin($_P, $_Data);
    }

    return $_Res;
}

/**
 * 获取中文拼音
 * @param $_Num
 * @param $_Data
 */
function _Pinyin($_Num, $_Data) {
    if ($_Num > 0 && $_Num < 160)
        return chr($_Num);
    elseif ($_Num < -20319 || $_Num > -10247)
        return '';
    else {
        foreach ($_Data as $k => $v) {
            if ($v <= $_Num)
                break;
        }
        return $k;
    }
}

/**
 * 获取中文拼音
 * @param $_C
 */
function _U2_Utf8_Gb($_C) {
    $_String = '';
    if ($_C < 0x80)
        $_String .= $_C;
    elseif ($_C < 0x800) {
        $_String .= chr(0xC0 | $_C >> 6);
        $_String .= chr(0x80 | $_C & 0x3F);
    } elseif ($_C < 0x10000) {
        $_String .= chr(0xE0 | $_C >> 12);
        $_String .= chr(0x80 | $_C >> 6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
    } elseif ($_C < 0x200000) {
        $_String .= chr(0xF0 | $_C >> 18);
        $_String .= chr(0x80 | $_C >> 12 & 0x3F);
        $_String .= chr(0x80 | $_C >> 6 & 0x3F);
        $_String .= chr(0x80 | $_C & 0x3F);
    }
    return iconv('UTF-8', 'GB2312', $_String);
}

/**
 * 获取中文拼音
 * @param unknown_type $_Arr1
 * @param unknown_type $_Arr2
 */
function _Array_Combine($_Arr1, $_Arr2) {
    for ($i                = 0; $i < count($_Arr1); $i++)
        $_Res[$_Arr1[$i]] = $_Arr2[$i];
    return $_Res;
}

/**
 * 获取随机标签颜色
 * @param int $num
 * @return mixed
 */
function getRandColor($num = 1) {
    $color = array(
        '#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500',
        '#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF',
        '#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE',
        '#CCCCCC', '#999999', '#666666', '#333333', '#000000'
    );
    return $color[array_rand($color)];
}

/**
 * 获取文件大小，filesize只对小于2GB的文件能正确获取
 * @param $path 文件路径
 * @param $danwei 返回的大小但闻  ＭＢ，ＫＢ，ＢＹＴＥ
 */
function getFileSize($path, $danwei = 'KB') {
    if (file_exists($path) && !is_dir($path)) {
        $file_size = filesize($path);
    } else {
        return '';
    }
    if ($file_size > 0) {
        switch (strtoupper($danwei)) {
            case 'MB':
                return number_format($file_size / 1024 / 1024, 0);
                break;
            case 'KB':
                return number_format($file_size / 1024, 0);
                break;
            case 'B':
                return number_format($file_size, 0);
                break;
            default:return '';
                break;
        }
    } else {
        return '';
    }
}


/**
 * 向字符串指定位置插入字符
 * @param string $str 字符串
 * @param int $pos 位置
 * @param string $ins 要插入的字符
 */
function insertStr($str, $pos, $ins) {
    $count = strlen($str);
    if ($count >= $pos) {
        $pre  = substr($str, 0, $pos);
        $last = substr($str, $pos);
        return $pre . $ins . $last;
    } else {
        return $str;
    }
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    $str = strip_tags(trim(preg_replace('/\s+/', '', $str)));
    if (function_exists("mb_substr")) {
        $slice = mb_substr($str, $start, $length, $charset);
    } elseif (function_exists('iconv_substr')) {
        $slice = iconv_substr($str, $start, $length, $charset);
        if (false === $slice) {
            $slice = '';
        }
    } else {
        $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice        = join("", array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice . '...' : $slice;
}

// 自动转换字符集 支持数组转换
function auto_charset($fContents, $from = 'gbk', $to = 'utf-8') {
    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to   = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key             = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key)
                unset($fContents[$key]);
        }
        return $fContents;
    }
    else {
        return $fContents;
    }
}

/**
 * 数组搜索
 * @param unknown_type $list
 * @param unknown_type $condition
 * @return multitype:unknown
 */
function search($list, $condition) {
    if (is_string($condition))
        parse_str($condition, $condition);
    $resultSet = array();
    foreach ($list as $key => $data) {
        $find = false;
        foreach ($condition as $field => $value) {
            if (isset($data[$field])) {
                if (0 === strpos($value, '/')) {
                    $find = preg_match($value, $data[$field]);
                } elseif ($data[$field] == $value) {
                    $find        = true;
                }
            }
        }
        if ($find)
            $resultSet[] = &$list[$key];
    }
    return $resultSet;
}

/**
 * 颜色随机
 * @return string
 */
function rcolor() {
    $rand = rand(0, 255);
    return sprintf("%02X", "$rand");
}

/**
 * 随机颜色
 * @return string
 */
function rand_color() {
    return '#' . rcolor() . rcolor() . rcolor();
}

/* 密码处理 */

function pwdHash($password, $type = 'md5') {
    return hash($type, $password);
}

/**
 * 可逆加密
 * @param unknown_type $str
 * @return string
 */
function myEncode($str) {
    return base64_encode($str . mt_rand(1000, 9999));
}

/**
 * 可逆解密
 * @param unknown_type $str
 * @return string
 */
function myDecode($str) {
    return substr(base64_decode($str), 0, -4);
}

/* 显示文件扩展名 */

function showExt($ext, $pic = true) {
    static $_extPic = array(
'dir'    => "folder.gif",
 'doc'    => 'msoffice.gif',
 'rar'    => 'rar.gif',
 'zip'    => 'zip.gif',
 'txt'    => 'text.gif',
 'pdf'    => 'pdf.gif',
 'html'   => 'html.gif',
 'png'    => 'image.gif',
 'gif'    => 'image.gif',
 'jpg'    => 'image.gif',
 'php'    => 'text.gif',
    );
    static $_extTxt = array(
'dir' => '文件夹',
 'jpg' => 'JPEG图象',
    );
    if ($pic) {
        if (array_key_exists(strtolower($ext), $_extPic)) {
            $show = "<IMG SRC='" . __ROOT__ . '/Public' . "/Images/extension/" . $_extPic[strtolower($ext)] . "' BORDER='0' alt='' align='absmiddle'>";
        } else {
            $show = "<IMG SRC='" . __ROOT__ . '/Public' . "/Images/extension/common.gif' WIDTH='16' HEIGHT='16' BORDER='0' alt='文件' align='absmiddle'>";
        }
    } else {
        if (array_key_exists(strtolower($ext), $_extTxt)) {
            $show = $_extTxt[strtolower($ext)];
        } else {
            $show = $ext ? $ext : '文件夹';
        }
    }

    return $show;
}

function clearCache($path, $exts = array('php', 'log')) {
    //遍历目录取得文件信息
    $i      = 0;
    if ($handle = opendir($path)) {
        while (false !== ($filename = readdir($handle))) {
            if ($filename{0} == '.') {
                continue;
            }
            $file     = $path . $filename;
            $file_ext = strtolower(array_pop(explode('.', trim($file))));
            if (is_dir($file)) {
                clearCache($file . '/', $exts);
            } else if (!in_array($file_ext, $exts)) {
                continue;
            } else {
                if (file_exists($file)) {
                    @unlink($file);
                    $i++;
                }
            }
        }
        closedir($handle);
    }
    return $i;
}

//验证码
function createCaptcha($imageH = 22, $imageL = 80, $length = 4, $size = 16, $bg = array(255, 255, 255), $curve = false, $Noise = false) {
    import("ORG.Captcha.Captcha");

    Captcha::$expire = 3000;     // 验证码过期时间（s）
    Captcha::$useZh = false;    // 使用中文验证码 
    Captcha::$useImgBg = false;    // 使用背景图片 
    Captcha::$fontSize = $size;      // 验证码字体大小(px)
    Captcha::$useCurve = $curve;    // 是否画混淆曲线
    Captcha::$useNoise = $Noise;    // 是否添加杂点	
    Captcha::$imageH = $imageH;       // 验证码图片高
    Captcha::$imageL = $imageL;      // 验证码图片宽
    Captcha::$length = $length;        // 验证码位数
    Captcha::$bg = $bg;   //背景色

    Captcha::entry();      // 输出图片
}

/**
 * 邮件发送，需引入库文件
 * 	$smtpserver     //smtp服务器
 * 	$user_mail		//发件人邮箱
 * 	$emailto		//收件人邮箱
 * 	$subject		//邮件主题
 * 	$body			//邮件内容
 *  $auth			//bool true
 * 	$auth_user		//验证用户名
 * 	$auth_pass		//验证用户密码
 * 	$type			//邮件发送格式（HTML/TXT）
 * 	$port			//smtp端口
 * @return 
 */
function send_email($emailto, $subject, $body, $smtpserver = '', $user_mail = '', $auth = true, $auth_user = '', $auth_pass = '', $type = 'HTML', $port = 25) {
    import("ORG.Util.Smtp");

    if (empty($smtpserver)) {
        $smtpserver = $GLOBALS['CFG']['EMAIL_SMTP'];
    }
    if (empty($user_mail)) {
        $user_mail = $GLOBALS['CFG']['EMAIL_USER_EMAIL'];
    }
    if (empty($auth_user)) {
        $auth_user = $GLOBALS['CFG']['EMAIL_AUTH_USER'];
    }
    if (empty($auth_pass)) {
        $auth_pass = substr(base64_decode($GLOBALS['CFG']['EMAIL_AUTH_PWD']), 0, -4);
    }
    //echo $body;exit;
    $smtp      = new Smtp($smtpserver, $port, $auth, $auth_user, $auth_pass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
    $smtp->debug = false;        //是否显示发送的调试信息
    if ($smtp->sendmail($emailto, $user_mail, $subject, $body, $type)) {
        return true;
    } else {
        return false;
    }
}

/* 获取真实IP */

function get_real_ip() {
    static $realip = NULL;
    if ($realip !== NULL) {
        return $realip;
    }
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip) {
                $ip = trim($ip);
                if ($ip != 'unknown') {
                    $realip = $ip;
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            } else {
                $realip = '0.0.0.0';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

//过滤空数组元素回调函数
function array_none($var) {
    if (!empty($var)) {
        return true;
    }
}

//浏览文件夹
function get_file_list($flash_exts = array('flv'), $current_path = '../flashs/') {
    //遍历目录取得文件信息
    //$photo_exts = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    //$flash_exts = array('swf');
    //$current_path='../flashs/';
    $file_list = array();

    if ($handle = opendir($current_path)) {
        $i        = 0;
        while (false !== ($filename = readdir($handle))) {
            if ($filename{0} == '.')
                continue;
            $file     = $current_path . $filename;
            $file_ext = strtolower(array_pop(explode('.', trim($file))));
            if (is_dir($file)) {
                continue;
                /* $file_list[$i]['is_dir'] = true; //是否文件夹
                  $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
                  $file_list[$i]['filesize'] = 0; //文件大小
                  $file_list[$i]['is_photo'] = false; //是否图片
                  $file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断 */
            } else if (!in_array($file_ext, $flash_exts)) {
                continue;
            } else {
                $file_list[$i]['is_dir']   = false;
                $file_list[$i]['has_file'] = false;
                $file_list[$i]['filesize'] = number_format(filesize($file) / 1024 / 1024, 2) . 'MB';
                $file_list[$i]['fullpath'] = iconv("gb2312", "utf-8", str_replace('../', '', $current_path) . $filename); //相对路径
                //$file_list[$i]['is_photo'] = in_array($file_ext, $photo_exts);
                //$file_list[$i]['is_flash'] = in_array($file_ext, $flash_exts);
                $file_list[$i]['filetype'] = $file_ext;
            }
            $file_list[$i]['filename'] = iconv("gb2312", "utf-8", $filename); //文件名，包含扩展名
            $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
            $i++;
        }
        closedir($handle);
    }

    usort($file_list, 'cmp_func');

    return $file_list;
}

//排序，文件夹在前
function cmp_func($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    } else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            } else if ($a['filesize'] < $b['filesize']) {
                return -1;
            } else {
                return 0;
            }
        } else if ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        } else {
            return strcmp($a['filename'], $b['filename']);
        }
    }
}

/**
 * 使用正则验证数据
 * @access public
 * @param string $value  要验证的数据
 * @param string $rule 验证规则
 * @return boolean
 */
function regex($value, $rule) {
    $validate = array(
        'require'  => '/.+/',
        'email'    => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        'mobile'   => '/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/',
        'url'      => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'time'     => '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/',
        'currency' => '/^\d+(\.\d+)?$/',
        'number'   => '/^\d+$/',
        'zip'      => '/^\d{6}$/',
        'qq'       => '/^\d{5,12}$/',
        'integer'  => '/^[-\+]?\d+$/',
        'double'   => '/^[-\+]?\d+(\.\d+)?$/',
        'english'  => '/^[A-Za-z]+$/',
        'chinese'  => '/^[\x{4e00}-\x{9fa5}]{1,}$/u', //这个小u修饰符用来识别utf-8中文
        'username' => '/^[a-zA-Z\x{4e00}-\x{9fa5}]{3,20}$/u', //这个小u修饰符用来识别utf-8中文
    );
    // 检查是否有内置的正则表达式
    if (isset($validate[strtolower($rule)])) {
        $rule = $validate[strtolower($rule)];
    }
    return preg_match($rule, $value) === 1;
}

/**
 * Curl单线程
 * Enter description here ...
 */
function FetchOne($url, $data = array(), $post = false) {

    $header = "Content-type: text/html";     //定义content-type为xml
    $curl   = curl_init();         //初始化curl
    curl_setopt($curl, CURLOPT_URL, $url);    //设置链接
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  //设置是否返回信息
    if ($post) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //设置HTTP头
        curl_setopt($curl, CURLOPT_POST, 1);    //设置为POST方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  //POST数据
    }
    $response = curl_exec($curl);      //接收返回信息
    if (curl_errno($curl)) {        //出错则显示错误信息
        echo curl_error($curl);
        exit;
    }
    curl_close($curl);          //关闭curl链接
    return $response;
}

function sexStr($val) {
    switch ($val) {
        case 'man':
            return '男';
            break;
        case 'women':
            return '女';
            break;
        default:
            return '保密';
            break;
    }
}

/**
 * 过滤得到安全的html
 * @param string $text 待过滤的字符串
 * @param string $type 默认为string,可选项:INT,FLOAT,BOOL,WORD,ALNUM,CMD,BASE64,ARRAY,PATH,USERNAME
 * @param bool $tagsMethod true为开启黑名单，白名单失效。false为开启白名单，黑名单失效.
 * @param bool $attrMethod 同上
 * @param array $tags 标签的过滤白名单
 * @param array $attr 属性名的过滤白名单
 * @param array $tagsBlack 标签的过滤黑名单
 * @param array $attrBlack 标签中属性的过滤黑名单
 */
//function h($text,$type,$tagsMethod=true,$attrMethod=true,$xssAuto = 1,$tags=array(),$attr=array(),$tagsBlack=array(),$attrBlack=array()){
//	if(!class_exists('Security')){
//		vendor('libs.SamLib.filter.Security','','.class.php');
//	}
//	$inputConfig ['tagsMethod'] = 1;  //默认开启黑名单
//	$inputConfig ['attrMethod'] = 1;  //默认开启黑名单
//	$inputConfig ['xssAuto'] = 1 ;    //默认开启黑名单
//	$inputConfig ['tagsFilter'] = array();  //默认白名单为空
//	$inputConfig ['attrFilter'] = array();  //默认白名单为空
//	$inputConfig ['tagBlacklist'] = array ('applet', 'body', 'bgsound', 'base', 'basefont', 'frame', 'frameset', 'head',
//											'html', 'id', 'iframe', 'ilayer', 'layer', 'link', 'meta', 'name',  'script',
//											'style', 'title', 'xml','vbscript','javascript','input','form','textarea','select','option','button'); //默认的黑名单
//	$inputConfig ['attrBlacklist'] = array ('action', 'codebase', 'dynsrc', 'lowsrc','onclick','onload','onsubmit'); //默认的黑名单
//
//
//
//	$filter = Security::getInstance($type,$inputConfig);
//
//	$filter->setTagsMethod($tagsMethod);
//	$filter->setAttrMethod($attrMethod);
//	$filter->setXss($xssAuto);
//	//白名单.当$tagsMethod=false的时候无效
//	!empty($tags) && $filter->setTagsFilter($tags);
//	!empty($attr) && $filter->setAttrFilter($attr);
//	//黑名单.当$tagsMethod=true时候有效
//	!empty($tagsBlack) && $filter->setTagBlacklist($tagsBlack);
//	!empty($attrBlack) && $filter->setAttrBlacklist($attrBlack);
//	return $filter->inputFilter($text);
//}

//输出纯文本
function text($text,$parseBr=false){
    $text = htmlspecialchars_decode($text);
    $text	=	safe($text,'text');
    if(!$parseBr){
        $text	=	str_ireplace(array("\r","\n","\t","&nbsp;"),'',$text);
        $text	=	htmlspecialchars($text,ENT_QUOTES);
    }else{
        $text	=	htmlspecialchars($text,ENT_QUOTES);
        $text	=	nl2br($text);
    }
    $text	=	trim($text);
    return $text;
}


function safe($text,$type='html',$tagsMethod=true,$attrMethod=true,$xssAuto = 1,$tags=array(),$attr=array(),$tagsBlack=array(),$attrBlack=array()){

    //无标签格式
    $text_tags	=	'';

    //只存在字体样式
    $font_tags	=	'<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>';

    //标题摘要基本格式
    $base_tags	=	$font_tags.'<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>';

    //兼容Form格式
    $form_tags	=	$base_tags.'<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>';

    //内容等允许HTML的格式
    $html_tags	=	$base_tags.'<ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed>';

    //专题等全HTML格式
    $all_tags	=	$form_tags.$html_tags.'<!DOCTYPE><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>';

    //过滤标签
    $text	=	strip_tags($text, ${$type.'_tags'} );

        //过滤攻击代码
        if($type!='all'){
            //过滤危险的属性，如：过滤on事件lang js
            while(preg_match('/(<[^><]+) (onclick|onload|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background|codebase|dynsrc|lowsrc)([^><]*)/i',$text,$mat)){
                $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
            }
            while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
                $text	=	str_ireplace($mat[0],$mat[1].$mat[3],$text);
            }
        }
        return $text;
}

?>